<?php

class DrillController extends GxController {

    public $pageTitle = "Drills Editor";
    public $backurl;
    public $view_css = "/css/views/drill.css";


    public function actionList() {

        $criteria=new CDbCriteria;

        if (isset($_REQUEST['category'])) {
            if($_REQUEST['category']!="") {
                $criteria->compare('category', $_REQUEST['category']);
            }
        }

        $criteria->order = 'id DESC';
        if (isset($_REQUEST['Drill_sort'])) {
            if($_REQUEST['Drill_sort']=="name") {
                $criteria->order = 'name ASC';
            }
            else if($_REQUEST['Drill_sort']=="name.desc") {
                $criteria->order = 'name DESC';
            }
            else if($_REQUEST['Drill_sort']=="category") {
                $criteria->order = 'category ASC';
            }
            else if($_REQUEST['Drill_sort']=="category.desc") {
                $criteria->order = 'category DESC';
            }
            else if($_REQUEST['Drill_sort']=="players") {
                $criteria->order = 'players ASC';
            }
            else if($_REQUEST['Drill_sort']=="players.desc") {
                $criteria->order = 'players DESC';
            }
        }

        if (isset($_REQUEST['mode'])) {
            $_SESSION["drill-library-mode"] = $_REQUEST['mode'];
        }

            $this->allowUsers(Array(),Array());
        $dataProvider = new CActiveDataProvider('Drill',array("criteria"=>$criteria,"pagination"=>array("pageSize"=>Yii::app()->params['defaultPageSize'])));
        $this->pageTitle = "Drills Library";
        $this->layout = '/layouts/main';
        $this->backurl = "";
        $this->render('list', array(
            'dataProvider' => $dataProvider,
        ));
    }


	public function actionShow($id) {
        $model = $this->loadModel($id, 'drill');
        $this->allowUsers(Array(),Array());
        $this->pageTitle = "Drills Library : \"".$model->name."\"";
        $this->layout = '/layouts/main';
        $this->backurl = "list";
        $this->render('show', array(
            'model' => $model,
        ));
    }



    public function actionView($id) {

        // Get data
        $model = $this->loadModel($id, 'drill');
        $diagrams = DrillDiagram::model()->GetDrillDiagrams($model->id);
        $tags = DrillTag::model()->GetDrillTags($model->id);

        // Filter the access (we need $model for this)
        $this->allowUsers(Array("admin"),Array($model->author));

        $this->pageTitle .= " : \"".$model->name."\" Details";
        $this->layout = '/layouts/main';
        $this->backurl = "admin";
        $this->render('view', array(
            'model' => $model,
            'diagrams' => $diagrams,
            'tags' => $tags
        ));
    }




	public function actionCreate() {
		$this->allowUsers(Array(),Array());
		$model = new Drill;


		if (isset($_POST['Drill'])) {
			$model->setAttributes($_POST['Drill']);
            $user = User::model()->find('username=?', array(Yii::app()->user->id));
            $model->author_id = $user->id;
            /*
			$relatedData = array(
				'tags' => $_POST['Drill']['tags'] === '' ? null : $_POST['Drill']['tags'],
				);

			if ($model->saveWithRelated($relatedData)) {
            */
            if ($model->save()) {
				if (Yii::app()->getRequest()->getIsAjaxRequest())
					Yii::app()->end();
				else
					$this->redirect(array('view', 'id' => $model->id));
			}
		}
        $this->pageTitle .= " : New";
        $this->layout = '/layouts/main';
        $this->backurl = "admin";
		$this->render('create', array( 'model' => $model));
	}



	public function actionUpdate($id) {
		$this->allowUsers(Array(),Array());
		$model = $this->loadModel($id, 'Drill');
        $owner = $model->author_id;


		if (isset($_POST['Drill'])) {
			$model->setAttributes($_POST['Drill']);
/*
			$relatedData = array(
				'tags' => $_POST['Drill']['tags'] === '' ? null : $_POST['Drill']['tags'],
				);
			if ($model->saveWithRelated($relatedData)) {
*/

            // make owner unchangable
            $model->author_id = $owner;
            if ($model->save()) {
                    $this->redirect(array('view', 'id' => $model->id));
                }
            }

		$this->pageTitle .= " : \"".$model->name."\"";
        $this->layout = '/layouts/main';
        $this->backurl = "admin";
		$this->render('update', array(
				'model' => $model,
				));
	}


    public function actionUpdateVideo($id) {
        $this->allowUsers(Array(),Array());
        $model = $this->loadModel($id, 'Drill');

        if (isset($_POST['youtube_url'])) {
            $video_id = BCApp::GetYouTubeVideoId($_POST['youtube_url']);
            if($video_id) {
                // change the youtube video id
                $model->youtube_id = $video_id;
                $model->save();
            }
            else {
                Yii::app()->user->setFlash("error","The inserted URL is not a valid Youtube URL");
            }
        }

        else if (isset($_POST['remove_video'])) {
            // change the youtube video id
            $model->youtube_id = "";
            $model->save();
        }

        $this->pageTitle .= " : \"".$model->name."\" Video Update";
        $this->layout = '/layouts/main';
        $this->backurl = "admin";

        $this->render('updatevideo', array(
            'model' => $model,
        ));
    }


    public function actionUpdateDiagrams($id) {
        $this->allowUsers(Array(),Array());
        $model = $this->loadModel($id, 'Drill');

        $this->pageTitle .= " : \"".$model->name."\" Diagrams Update";
        $this->layout = '/layouts/main';
        $this->backurl = "admin";

        $this->render('updatediagrams', array(
            'model' => $model,
        ));
    }

    public function actionCreateDraw($drill_id) {

        $this->allowUsers(Array(),Array());

        $model = new DrillDiagram;
        $model->drill_id = $drill_id;
        $model->type = "diag-half";
        $model->file_ext = "png";
        $model->weight = 1;
        $model->save();
        $this->redirect(array('updatedraw','id'=>$model->id));
    }



    public function actionUpdateDraw($id) {
        $this->allowUsers(Array(),Array());
        $model = $this->loadModel($id, 'DrillDiagram');

        if(isset($_REQUEST["do"])) {
            $do = $_REQUEST["do"];
            if($do=="save") {
                $res = CDrawer::Save("./images/diagrams",$model->id);
                $model->metadata = $res["data"];
                $model->type = $res["type"];
                $model->file_ext = $res["file_ext"];
                $model->save();
                $this->redirect(array('updatediagrams','id'=>$model->drill_id));
            }
        }

        $this->backurl = "drill/updatediagrams&id=".$model->drill_id;
        $this->render('updatedraw', array(
            'model' => $model,
        ));
    }



	public function actionDelete($id) {
	  $this->allowUsers(Array(),Array());
		if (Yii::app()->getRequest()->getIsPostRequest()) {
			$this->loadModel($id, 'Drill')->delete();

			if (!Yii::app()->getRequest()->getIsAjaxRequest())
				$this->redirect(array('admin'));
		} else
			throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
	}



	public function actionIndex() {
				$this->allowUsers(Array(),Array());
				$this->redirect(array('admin'));
	}


	public function actionAdmin() {
		$this->allowUsers(Array(),Array());
		$model = new Drill('search');
		$model->unsetAttributes();


		if (isset($_GET['Drill']))
			$model->setAttributes($_GET['Drill']);

        $this->layout = '/layouts/main';
		$this->render('admin', array(
			'model' => $model,
		));
	}


    public function actionPdfExport() {

        $this->allowUsers(Array(),Array());
        $model = new Drill('search');
        $this->layout = 'none';
        $this->render('pdfexport', array(
            'model' => $model,
        ));
    }

    
    public function actionExcelExport() {

        $this->allowUsers(Array(),Array());
        $model = new Drill('search');
        $this->layout = 'none';
        $this->render('excelexport', array(
            'model' => $model,
        ));
    }
    


}